package com.wangc.report.controller;

import com.wangc.report.dao.ConfigMapper;
import com.wangc.report.entity.DownloadEntity;
import com.wangc.report.service.ExportToExceService;
import com.wangc.report.utils.PageUtils;
import com.wangc.report.utils.Query;
import com.wangc.report.utils.R;
import com.wangc.report.utils.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author wangc
 * @email 1620415297@qq.com
 * @date 2020-10-20 14:13:37
 */
@RestController
@RequestMapping("/export")
public class ExportToExcelController {
    private static final Logger LOG = LoggerFactory.getLogger(ExportToExcelController.class);
    @Resource
    private ExportToExceService exportToExceService;
    @Resource
    private ConfigMapper configMapper;

    /**
     * 查看列表
     */
    @RequestMapping("/run")
    public R export(@RequestParam Map<String, Object> params) {
        if (null == params.get("tableId")) {
            throw new RRException("输入表为空请检查！");
        }
        String[] tableList = params.get("tableId").toString().split(",");
        for (String tableId : tableList) {
            exportToExceService.export(tableId.split("\\|")[1], tableId.split("\\|")[0]);
        }

        return R.ok();
    }

    /**
     * 查看列表
     */
    @RequestMapping("/download")
    public void download(@RequestParam Map<String, Object> params) {
        String[] tableList = params.get("tableId").toString().replace("\"", "").split(",");
        if (null == params.get("tableId")) {
            throw new RRException("输入表为空请检查！");
        }
        for (String tableId : tableList) {
            LOG.debug(tableId);
        }
        LOG.debug(tableList[0].split("\\|")[1]);
        String path = configMapper.selectByTableId(tableList[0].split("\\|")[1]).getFilePath();
        LOG.debug(path);
        String filename = path + tableList[0].split("\\|")[1] + "_" + tableList[0].split("\\|")[0] + ".xls";
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        String file = tableList[0].split("\\|")[1] + "_" + tableList[0].split("\\|")[0] + ".xls";
        // 设置编码
        String downloadFileName = null;
        try {
            downloadFileName = new String(file.getBytes("utf-8"), "iso-8859-1");
            // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type", new MimetypesFileTypeMap().getContentType(downloadFileName));

            OutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(new FileInputStream(new File(filename)));
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            throw new RRException(e.toString());
        }


    }

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<DownloadEntity> configList = exportToExceService.queryList(query);
        int total = configList.size();
        long i = 0l;
        for (DownloadEntity downloadEntity : configList) {
            downloadEntity.setId(downloadEntity.getDataDt() + "|" + downloadEntity.getTableId());
        }
        PageUtils pageUtil = new PageUtils(configList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }
}
